其他
值得开发者关注的 Java 8 后时代的语言特性
以下文章来源于阿里巴巴中间件 ,作者雷卷
首先我们必须承认,Java 8 是一个里程碑式的版本,这个相信大多数Java程序员都认同,其中最知名的是 Streams & Lambda ,这让 Functional Programming 成为可能,让 Java 换发新的活力。这也是即便 Oracle 不在支持 Java 8 的更新,各个云厂商还是积极支持,站点为 https://adoptopenjdk.net/ ,可以让 Java 8 能继续保留非常长的时间。
var 关键字(局部变量类型推导) Local-Variable Type Inference
Map<String, List<Map<String,Object>>> store = new ConcurrentHashMap<String, List<Map<String,Object>>>();
Map<String, List<Map<String,Object>>> store = new ConcurrentHashMap<>();
Map<String, List<Map<String,Object>>> store = new ConcurrentHashMap<String, List<Map<String,Object>>>();
//lambda
BiFunction<String, String, String> function1 = (var s1, var s2) -> s1 + s2;
System.out.println(function1.apply(text1, text2));
sudo cp bin/confd /usr/local/bin
confd
ProcessHandle
ProcessHandle ph = ProcessHandle.of(89810).get();
System.out.println(ph.info());
Collection factory methods
Set<Integer> ints = Set.of(1, 2, 3);
List<String> strings = List.of("first", "second");
String 类的新 API
HTTP 2支持
HttpClient client = HttpClient.newHttpClient();
HttpRequest req =
HttpRequest.newBuilder(URI.create("https://httpbin.org/ip"))
.header("User-Agent", "Java")
.GET()
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());
Text Block(JDK 13)
String jsonText = "{\"id\": 1, \"nick\": \"leijuan\"}";
//language=json
String cleanJsonText = """
{"id": 1, "nick": "leijuan"}""";
//language=html
String textBlock = """
<span style="color: green">Hello %s</span>""";
System.out.println(textBlock.formatted(nick));
Switch 提升
//legacy
switch (DayOfWeek.FRIDAY) {
case MONDAY: {
System.out.println(1);
break;
}
case WEDNESDAY: {
System.out.println(2);
break;
}
default: {
System.out.println("Unknown");
}
}
//Arrow labels
switch (DayOfWeek.FRIDAY) {
case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
case TUESDAY -> System.out.println(7);
case THURSDAY, SATURDAY -> System.out.println(8);
case WEDNESDAY -> System.out.println(9);
}
//Yielding a value
int i2 = switch (DayOfWeek.FRIDAY) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
default -> {
yield 10;
}
};
<dependency>
<groupId>com.github.bsideup.jabel</groupId>
<artifactId>jabel-javac-plugin</artifactId>
<version>0.2.0</version>
</dependency>
然后调整一下 maven 的 compiler plugin,将 source 设置为你想要的 Java 版本,如 13 , target 和 release 设置为 8 就可以啦。 IntelliJ IDEA 会自动识别,也不需要调整。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>13</source>
<target>8</target>
<release>8</release>
</configuration>
</plugin>
这样你就可以愉快地使用介绍的特性啦。
总结
参考
Java 10 Features:
Java 11 Features:
Java 12 Features:
Java 13 Features:
Java 14 Features:
雷卷,阿里巴巴资深技术专家,GitHub ID @linux-china。
如果大家想要实时关注我更新的文章以及分享的干货的话,可以关注我的公众号。
欢迎关注